package com.zerocarbon.framework.db.mybatis.typehandler;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 字段json字符串 转化
 * @author wyf
 * 2020年8月17日
 * @param <T>
 */
@Slf4j
public abstract class AbstractJsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName));
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex));
    }

    private String toJson(T object) {
        try {
        	return JSON.toJSONString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
	private T toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
            	T result = (T) JSON.parseObject(content, (Class<T>) getRawType());
            	//System.out.println(this.toString());
            	//System.out.println(result);
            	return result;
            } catch (Exception e) {
                //throw new RuntimeException(e);
            	log.error("解析字段内的json内容异常", e);
            	return null;
            }
        } else {
            return null;
        }
    }
}